package com.app.project;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.lang.reflect.Method;
import java.sql.ResultSet;
import java.util.Stack;
import java.util.TimerTask;
import java.util.UUID;

import com.google.android.gms.location.LocationClient;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.MapFragment;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothServerSocket;
import android.bluetooth.BluetoothSocket;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationManager;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.SystemClock;
import android.provider.Settings;
import android.text.format.Time;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Toast;

@SuppressLint("HandlerLeak")
public class Bluetooth_Service extends Activity{
	
	private BluetoothDevice device;
	private static final String Name = "Bluetooth Test";
	private static final UUID MY_UUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
	private static final int MASSAGE_READ = 100;
	private ConnectThread mConnectThread = null;
	private AcceptThread mAcceptThread = null;
	private ConnectedThread mConnectedThread = null;
	private BluetoothAdapter mBluetoothAdapter = null;
	private BluetoothSocket socket = null;
	private String mDeviceName = "Admin";
	private ListView mDataView;
	private ArrayAdapter<String> mArrayAdapter;
	private StringBuilder sb = new StringBuilder();
	private String Android_Command ="";
	private static final String Speed = "S";
	private static final String Balance = "B";
	private Handler Handler = new Handler();
//	
//	 EditText CarID,CarSpeed,CarBalance;
//	 Button buttonB,buttonS,buttonClear;
//		
    
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
//		setContentView(R.layout.activity_main_map);
//		CarID = (EditText) findViewById(R.id.A_Main_carid);
//	    CarSpeed = (EditText) findViewById(R.id.A_Main_carspeed);
//	    CarBalance = (EditText) findViewById(R.id.A_Main_Balance);
	}
	
	public void onResume() {
		super.onResume();

	}
	
	public class AcceptThread extends Thread{
		private final BluetoothServerSocket mmServerSocket;
		
		public AcceptThread(){
			BluetoothServerSocket tmp = null;
			try{
				tmp = mBluetoothAdapter.listenUsingRfcommWithServiceRecord(Name, MY_UUID);
			}catch(IOException e){
				
			}
			mmServerSocket = tmp;
		}
		
		public void run(){
			while(true){
				try{
					socket = mmServerSocket.accept();
				}catch(IOException e){
					break;
				}
				if(socket != null){
					mConnectedThread = new ConnectedThread(socket);
					mConnectedThread.start();
					try{
						mmServerSocket.close();
					}catch(IOException e){
						e.printStackTrace();
					}
					break;
				}
			}
		}
		@SuppressWarnings("unused")
		public void cancle(){
			try{
				mmServerSocket.close();
			}catch(IOException e){
				e.printStackTrace();
			}
		}
	}
	
	public class ConnectThread extends Thread{
		private final BluetoothSocket mmSocket;
		@SuppressWarnings("unused")
		private final BluetoothDevice mmDevice;
		
		public ConnectThread(BluetoothDevice device){
			BluetoothSocket tmp = null;
			mmDevice = device;
			try{
				tmp = device.createRfcommSocketToServiceRecord(MY_UUID);
			}catch(IOException e){
				
			}
			mmSocket = tmp;
		}
		
		public void run(){
			mBluetoothAdapter.cancelDiscovery();
			try{
				mmSocket.connect();
			}catch(IOException connectException){
				try{
					mmSocket.close();
				}catch(IOException closeException){
					
				}
				return;
				
			}
			mConnectedThread = new ConnectedThread(mmSocket);
			mConnectedThread.start();
		}
		
		@SuppressWarnings("unused")
		public void cancel(){
			try{
				mmSocket.close();
			}catch(IOException e){
				
			}
		}
	}
	
	public class ConnectedThread extends Thread{
		private final BluetoothSocket mmSocket;
		private final InputStream mmInStream;
		private final OutputStream mmOutStream;
		
		public ConnectedThread(BluetoothSocket socket){
			//Log.d("THREAD", "constructor");
			mmSocket = socket;
			InputStream tmpIn = null;
			OutputStream tmpOut = null;
			try{
				tmpIn = socket.getInputStream();
				tmpOut = socket.getOutputStream();
			}catch(IOException e){
				
			}
			mmInStream = tmpIn;
			mmOutStream = tmpOut;
		}
		

		public void run(){
			Log.d("THREAD", "inside run" );
			byte[] buffer =new byte[256];
			int bytes;
			while (true) {
//				Log.d("in loop", "waiting for data");
				try{
					bytes = mmInStream.read(buffer);
					mHandler.obtainMessage(MASSAGE_READ, bytes, -1,buffer).sendToTarget();
//					
					//SystemClock.sleep(1000);
//					Log.d("recieve", "b " + bytes);
				}catch(IOException e){
					break;
				}
				
			}
		}
		
		public void write(String message){
//			Log.d("TAG", "...Data to send: " + message + "...");
			byte[] msgBuffer = message.getBytes();
			try{
				mmOutStream.write(msgBuffer);
			}catch(IOException e){
//				Log.d("TAG", "...Error data send: " + e.getMessage() + "...");  
			}
		}
		@SuppressWarnings("unused")
		public void cancle(){
			try{
				mmSocket.close();
			}catch(IOException e){
				
			}
		}
	}
	
	private final Handler mHandler = new Handler(){
		public void handleMessage(android.os.Message msg) {
			switch (msg.what) {
			case MASSAGE_READ:
				byte[] readBuf = (byte[]) msg.obj;
				String strIncom = new String(readBuf, 0, msg.arg1);
				mArrayAdapter.add("Arduino : "+strIncom.toString());
				sb.append(strIncom);												// append string
            	int endOfLineIndex = sb.indexOf("\r\n");							// determine the end-of-line
            	if (endOfLineIndex > 0) { 											// if end-of-line,
            		String sbprint = sb.substring(0, endOfLineIndex);				// extract string
                    sb.delete(0, sb.length());
                    if(Android_Command.equals(Speed)){
//                    	CarSpeed.setText(sbprint); 
                    }else if(Android_Command.equals(Balance)){
//                    	CarBalance.setText(sbprint); 
                    }
                }
     
                break;
                
			}
			
		}
	};


	public void SentComman(String Comman) {
		// TODO Auto-generated method stub
    	mConnectedThread.write(Comman);
	}
	

}
